<template>
	<div>
	</div>
</template>
<script>
	let barcodeVue = {
		name: "Barcodescan",
		props: {
			shopName: {
				type: String
			}
		},
		data() {
			return {
				realBarcode: "",
				keyupLastTime: undefined,
				name: undefined,
				regexRules: []
			};
		},
		created() {
			let that = this;
			// 监听页面的keyup事件
			document.onkeyup = function(e) {
				that.handleKeyUp(e);
			};
			this.name = this.shopName;
			this.initRegexRules();
		},
		methods: {
			// 初始化条码规则（自定义）
			initRegexRules() {
				this.regexRules = [{
						regex: "/^IN(\\w|\\d)+$/",
						value: "putInStorageNumber"
					},
					{
						regex: "/^CH(\\w|\\d)+$/",
						value: "checkNumber"
					},
					{
						regex: "/^AL(\\w|\\d)+$/",
						value: "allocateNumber"
					},
					{
						regex: "/^\\d{12}$/",
						value: "orderNumber"
					},
					{
						regex: "/^SR(\\w|\\d)+$/",
						value: "transferNumber"
					},
					{
						regex: "/^\\d{12}-\\d{3}$/",
						value: "sendNo"
					},
					{
						regex: "/^PL\\d{10}$/",
						value: "wavePickingNumber"
					},
					{
						regex: "/^PL\\d{10}-\\d{3}$/",
						value: "wavePickingGroupNumber"
					},
					{
						regex: "/^(\\w|\\d)*-[\\w|\\d]*-\\d*-[A-Z]-\\d*/",
						value: "location"
					}
				]
			},
			// 处理keyup事件
			handleKeyUp(e) {
				let gap = 0;
				if (this.keyupLastTime) {
					gap = new Date().getTime() - this.keyupLastTime;
					if (gap > 50) {
						gap = 0;
						this.realBarcode = "";
					}
				}
				this.keyupLastTime = new Date().getTime();
				if (e.key == undefined) {
					return
				}
				// 输入法会触发keyup事件，key为Process，跳过即可
				if (e.key != "Process" && gap < 50) {
					if (e.key.trim().length == 1) {
						// 输入单个字母或者数字
						this.realBarcode += e.key;
					} else if (e.key.trim() == "Enter") {
						console.log(e.key)
						// 根据规则，判断barcode类型，返回数据（自定义规则）
						if (this.realBarcode) {
							let data = {
								type: this.barcodeRule(this.realBarcode),
								code: this.realBarcode,
								isLocal: this.isLocal(this.realBarcode)
							};
							this.$emit('handle', data);
							this.realBarcode = "";
						}
					}
				}
			},
			// 判断条码类型，如果没找到，则返回类型为barCode
			barcodeRule(barcode) {
				let value;
				this.regexRules.some((item, index) => {
					let regex = eval(item.regex);
					if (regex.test(barcode)) {
						value = item.value;
						return true;
					}
				})
				return value ? value : "barCode";
			},
			// 根据条码是否包含门店名，判断是否本地条码
			isLocal(barcode) {
				return this.name ? barcode.indexOf(this.name) != -1 : undefined;
			}
		},
	};

	export default {
		...barcodeVue
	};
</script>
